<template>
  <div class="questionnaire-detail">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="答题分析" name="analysis">
        <div class="header">
          <h2>{{ title }}</h2>
          <p v-if="description">{{ description }}</p>
        </div>
        <!-- 加载中动画 -->
        <div v-if="loading" class="loading">
          <el-spinner></el-spinner>
          <span>加载中...</span>
        </div>

        <!-- 问卷数据展示 -->
        <div v-else>
          <el-row :gutter="20">
            <el-col :span="24" v-for="(question, index) in questions" :key="index">
              <div class="question-title">
                <h3>{{ question.question.content || '问题标题缺失' }}</h3>
                <span class="question-type">[{{ getQuestionType(question.question.type) }}]</span>
                <el-button v-if="question.question.type === 'text'" size="small"
                  @click="viewDetail(question.question.id, 'question')">查看详情</el-button>
              </div>

              <el-table :data="question.options" border style="width: 100%;color: black;" :stripe="true" size="medium"
                v-if="question.options && question.options.length > 0">
                <el-table-column prop="optionName" label="选项名称" min-width="150" align="center" />
                <el-table-column prop="optionContent" label="选项内容" min-width="250" />
                <el-table-column prop="count" label="选择次数" min-width="120" align="center" />
                <!-- 添加比例列 -->
                <el-table-column label="选择比例" min-width="200" align="center">
                  <template v-slot="scope">
                    <el-progress :percentage="getPercentage(scope.row.count,question)" stroke-width="5" />
                    <!-- <span>{{ getPercentage(scope.row.count,question) }}%</span> -->
                  </template>
                </el-table-column>
                <!-- <el-table-column label="操作" min-width="150" align="center">
                  <template v-slot="scope">
                    <el-button v-if="scope.row.optionContent && scope.row.optionContent.includes('其他')" size="small"
                      @click="viewDetail(scope.row.id, 'option')">查看详情</el-button>
                  </template>
                </el-table-column> -->
              </el-table>
              <!-- 显示有效填写人次 -->
              <el-row :gutter="20" v-if="question.options && question.options.length > 0">
                <el-col :span="24">
                  <div class="valid-fill-count">
                    <span>本题有效填写人次：</span>
                    <span>{{ getValidFillCountForQuestion(question) }}</span> <!-- 显示有效填写人次 -->
                  </div>
                </el-col>
              </el-row>

              <div v-else>
                <p>该问题没有选项数据</p>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-dialog v-model="dialogVisible" title="选项详情" :width="'80%'" @close="handleDialogClose">
          <el-table :data="optionDetails" style="width: 100%" border size="medium" :stripe="true">
            <el-table-column prop="createTime" label="创建时间" width="150" />
            <template v-if="currentType === 'option'">
              <el-table-column prop="optionContent" label="选项内容" />
              <el-table-column prop="optionName" label="选项名称" />
              <el-table-column prop="text" label="填写内容" />
            </template>
            <template v-else-if="currentType === 'question'">
              <el-table-column prop="queContent" label="简答题内容" />
              <el-table-column prop="text" label="回答内容" />
            </template>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-pagination :current-page="page" :page-size="pageSize" :total="totalItems"
              @current-change="handlePageChange" />
          </div>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane label="下载问卷" name="download">
        <el-card shadow="never">
          <div class="download-toolbar">
            <div class="filters">
              <!-- <el-input v-model="dlQuery.titleKeyword" placeholder="题目名称" clearable style="width:220px" /> -->
              <el-date-picker v-model="dlQuery.dateRange" type="daterange" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" style="margin-left:12px" />
              <el-button type="primary" style="margin-left:12px" @click="handleDlSearch">查询</el-button>
              <el-button style="margin-left:8px" @click="handleDlReset">重置</el-button>
            </div>
            <div class="actions">
              <el-button type="primary" @click="exportDlCsv">下载</el-button>
              <!-- <el-button type="primary" @click="downloadAnswerSheet({ userIds: ['1785264101257936094'] })">下载2</el-button> -->
            </div>
          </div>

          <!-- <div class="download-debug">
            <el-switch v-model="dlDebug" active-text="调试信息" inactive-text="调试信息" />
            <div v-if="dlDebug" class="debug-box">
              <div>records: {{ dlDebugInfo.count }}</div>
              <div>列prop: {{ dlColumns.map(c => c.key).join(', ') }}</div>
              <div>列名: {{ dlColumns.map(c => c.label).join(', ') }}</div>
              <div>首条answerPageVOs: {{ dlDebugInfo.firstKeys.join(', ') }}</div>
              <div>首行keys: {{ dlDebugInfo.firstRowKeys.join(', ') }}</div>
            </div>
          </div> -->
          <!-- 显示加载中动画 -->
          <div v-if="dlLoading" class="loading">
            <el-spinner></el-spinner>
            <span>加载中...</span>
          </div>

          <el-table v-if="!dlLoading" :data="dlList" border style="width: 100%; color: black;" :stripe="true"
            size="medium">
            <el-table-column prop="createTime" label="提交时间" min-width="180" align="center" />
            <el-table-column v-for="col in dlColumns" :key="col.key" :prop="col.key" :label="col.label" min-width="200"
              :fixed="col.key === 'createTime' ? 'left' : null" />
          </el-table>

          <div class="download-pagination">
            <el-pagination :current-page="dlPage" :page-size="dlPageSize" :total="dlTotal"
              @current-change="handleDlPageChange" />
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'

const route = useRoute()

// 页面数据
const title = route.query.title
const description = route.query.description || '暂无描述'
const qid = route.params.id
const loading = ref(true)
const questions = ref([])
const activeTab = ref('analysis')
const dlColumns = ref([])
const dlList = ref([])
const dlLoading = ref(false)
const dlPage = ref(1)
const dlPageSize = ref(10)
const dlTotal = ref(0)
const dlQuery = ref({ titleKeyword: '', dateRange: [] })
const dlDebug = ref(false)
const dlDebugInfo = ref({ count: 0, firstKeys: [], firstRowKeys: [] })

// 弹窗数据
const dialogVisible = ref(false)
const optionDetails = ref([])  // 弹窗中的选项详情
const page = ref(1)  // 当前页
const pageSize = ref(10)  // 每页显示的条数
const totalItems = ref(0)  // 总条数
const currentId = ref(null)   // 当前弹窗对应的 questionId 或 optionId
const currentType = ref('')   // 'question' 或 'option'

// 获取问题类型的描述
const getQuestionType = (type) => {
  switch (type) {
    case 'radio':
      return '单选题';
    case 'checkbox':
      return '多选题';
    case 'text':
      return '填空题';
    default:
      return '未知类型';
  }
}


// 计算选择比例
const getPercentage = (count, question) => {
  const totalCount = getValidFillCountForQuestion(question) // 使用现有的函数计算总填写人次
  if (totalCount === 0) return 0
  return Math.round((count / totalCount) * 100)
}

// 计算有效填写人次
const getValidFillCountForQuestion = (question) => {
  return question.options.reduce((total, option) => total + option.count, 0)
}

// 获取问卷分析数据
// 异步请求问卷分析接口，处理成功响应和错误情况
const fetchQuestionnaireData = async () => {
  try {
    const response = await request.get(`/questionnaire/questionnaireAnalysis/${qid}`)
    questions.value = response.data.data || []
    console.log('questions:', questions.value)
    if(response.data.code === 500)
  {
    ElMessage.error(response.data.message)
  }
  } catch (error) {
    ElMessage.error(error.message)

  } finally {
    loading.value = false
  }
}



// 查看详情的处理函数（简答题或“其他”选项）
const viewDetail = async (id, type) => {
  dialogVisible.value = true
  currentId.value = id
  currentType.value = type
  page.value = 1  // 打开弹窗时重置页码
  await fetchOptionDetails()
}

// 获取选项/简答详情
const fetchOptionDetails = async () => {
  if (!currentId.value) return
  try {
    let params = {
      current: page.value,
      size: pageSize.value
    }
    
    if (currentType.value === 'question') {
      params.queId = currentId.value
    } else if (currentType.value === 'option') {
      params.optid = currentId.value
    }

    const response = await request.get('/option/optionDetail', { params })
    optionDetails.value = response.data.data.records || []
    totalItems.value = response.data.data.records.length || 0
  } catch (error) {
    ElMessage.error('加载详情失败')
  }
}

// 分页切换
const handlePageChange = (newPage) => {
  page.value = newPage
  fetchOptionDetails()
}

// 弹窗关闭处理
const handleDialogClose = () => {
  optionDetails.value = []  // 清空数据
  currentId.value = null
  currentType.value = ''
  page.value = 1
}

// 下载问卷
const downloadQuestionnaire = async () => {
  try {
    const response = await request.get(`/questionnaire/export/${qid}`, { responseType: 'blob' })
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    const disposition = response.headers['content-disposition'] || ''
    const match = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/)
    const filename = decodeURIComponent((match && (match[1] || match[2])) || `问卷_${title || qid}.xlsx`)
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    a.remove()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

const buildDlColumns = () => {
  dlColumns.value = []  // 确保每次重新生成列时清空数组
  
  // 遍历 questions 数据，根据 answerPageVOs 动态生成列
  questions.value.forEach((q) => {
    const questionId = q?.question?.id
    const questionContent = q?.question?.content || ''

    // 如果 questionId 和 content 存在，动态添加列
    if (questionId && questionContent) {
      dlColumns.value.push({
        key: `qid_${questionId}`,
        label: questionContent,
      })
    }
  })

  // 添加提交时间列
  // dlColumns.value.unshift({
  //   key: 'createTime',
  //   label: '提交时间',
  //   fixed: 'left'
  // })
}


// 修改 `fetchDownloadList` 确保 `dlColumns` 在数据加载后同步更新
const fetchDownloadList = async () => {
  dlLoading.value = true
  try {
    const params = { qid, page: dlPage.value, size: dlPageSize.value, startTime: dlQuery.value.dateRange?.[0], endTime: dlQuery.value.dateRange?.[1] }
    const response = await request.get('/answer/listAnswer', { params })
    const payload = response.data || {}
    const records = payload?.data?.records || payload?.records || []
    const total = payload?.data?.total ?? payload?.total

    // 列映射：queId -> 问题内容（列名）
    const colMap = new Map()
    const rows = records.map((rec) => {
      const row = { createTime: rec.answerPageVOs[0].createTime || '暂无提交时间' }
      const groupedByQid = new Map()

      // 兼容空或缺失的 answerPageVOs
      const answers = Array.isArray(rec.answerPageVOs) ? rec.answerPageVOs : []

      // 遍历并按 queId 聚合（多选题会有多个答案，合并为一个单元格）
      answers.forEach((ans) => {
        const key = String(ans.queId || '')
        const value = (ans?.optContent || ans?.text || '').trim()
        if (!key) return

        if (!groupedByQid.has(key)) groupedByQid.set(key, [])
        if (value) groupedByQid.get(key).push(value)

        // 记录列头（首次出现时）
        if (!colMap.has(key)) {
          const label = (ans && ans.content) ? String(ans.content) : `问题 ${key}`
          colMap.set(key, label)
        }
      })

      // 将聚合的答案写入行数据（用顿号连接）
      for (const [k, arr] of groupedByQid.entries()) {
        row[k] = arr.join('、')
      }

      return row
    })

    // 生成列配置（保持首次出现顺序）
    dlColumns.value = Array.from(colMap.entries()).map(([key, label]) => ({ key, label }))

    dlList.value = rows
    dlTotal.value = typeof total === 'number' ? total : rows.length
  } catch (e) {
    ElMessage.error('下载列表加载失败')
    dlList.value = []
    dlTotal.value = 0
    dlColumns.value = []
  } finally {
    dlLoading.value = false
    // nextTick(() => {
    //   console.log('dlList.value',dlList.value);
    //   dlList.value = [...dlList.value]
    // })
  }
}


const handleDlPageChange = (p) => {
  dlPage.value = p
  fetchDownloadList()
}

const handleDlSearch = () => {
  dlPage.value = 1
  fetchDownloadList()
}

const handleDlReset = () => {
  dlQuery.value = { titleKeyword: '', dateRange: [] }
  dlPage.value = 1
  fetchDownloadList()
}

const exportDlCsv = () => {
  const header = ['提交时间', ...dlColumns.value.map(c => c.label)]
  const rows = dlList.value.map(r => [r.createTime, ...dlColumns.value.map(c => (r[c.key] || '').replace(/\n/g,' '))])
  const csv = [header, ...rows].map(row => row.map(cell => `"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\r\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `问卷_${title || qid}_导出.csv`
  document.body.appendChild(a)
  a.click()
  a.remove()
  URL.revokeObjectURL(url)
}
const downloadAnswerSheet = async (params) => {
      try {
        const response = await request({
          url: '/answer/export',  // 调用导出接口
          method: 'get',
          params,  // 查询参数
          responseType: 'blob'  // 返回的内容类型是二进制
        });

        const blob = response.data;
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '答卷.xlsx';  // 设置下载文件的名字
        document.body.appendChild(a);
        a.click();
        a.remove();

        // 释放 URL 对象
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error('下载失败', error);
      }
    };



// 页面加载时执行
onMounted(() => {
  fetchDownloadList()
  fetchQuestionnaireData().then(() => buildDlColumns())
})
</script>


<style scoped>
/* 整体页面容器 */
.questionnaire-detail {
  padding: 30px 40px;
  background-color: #f8f9fa; /* Element Plus Pro 风格的浅灰背景 */
  border-radius: 8px; /* 圆角效果 */
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08); /* 轻微的阴影 */
}

/* 顶部标题 */
.header {
  margin-bottom: 20px;
  text-align: center;
  color: #3c4a68; /* 深色标题 */
}

h2 {
  font-size: 26px;
  font-weight: 600;
  color: #2f3b52; /* 标题颜色 */
  margin-bottom: 8px;
}

/* 问题标题和类型 */
.question-title {
  display: flex;
  justify-content: space-between; /* 问题标题和类型分开 */
  align-items: center;
  margin-bottom: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #dcdfe6; /* 边框细化 */
}

.question-title h3 {
  font-size: 18px;
  font-weight: 500;
  color: #2f3c57; /* 问题标题颜色 */
  margin-right: 10px;
}

.question-type {
  font-size: 14px;
  color: #7a8a9c; /* 更柔和的灰色 */
  font-weight: 400;
}

/* 按钮样式 */
.el-button {
  background-color: #409eff; /* 主按钮色 */
  color: white;
  border-radius: 6px; /* 圆角 */
  padding: 8px 18px;
  transition: background-color 0.3s ease;
}

.el-button:hover {
  background-color: #66b1ff; /* 悬停时变化 */
}

.el-table {
  margin-top: 20px;
  width: 100%;
  border-radius: 8px; /* 表格圆角 */
  background-color: #fff; /* 白色背景 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); /* 添加轻微阴影 */
}

.el-table th {
  background-color: #f5f7ff; /* 表头背景色 */
  text-align: center;
  font-weight: 600;
  color: #3c4a68; /* 深色表头文字 */
}

.el-table th, .el-table td {
  padding: 12px 16px;
  border: 1px solid #e6e9f1; /* 更细的边框 */
}

.el-table .cell {
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-card {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px; /* 卡片圆角 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); /* 卡片阴影 */
  padding: 16px;
}

/* 下载区的工具条 */
.download-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06); /* 工具条阴影 */
}

.filters {
  display: flex;
  align-items: center;
}

.actions {
  display: flex;
  align-items: center;
}

.el-date-picker {
  margin-left: 12px;
}

.el-button[type='primary'] {
  background-color: #409eff;
  color: white;
  font-size: 14px;
  border-radius: 6px;
}

.el-button[type='primary']:hover {
  background-color: #66b1ff;
}

.download-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table__header {
  background-color: #f9f9f9; /* 更浅的背景 */
  font-weight: 600;
  color: #555; /* 更柔和的颜色 */
}

.el-table__row {
  border-bottom: 1px solid #f4f6fc;
}

.el-table__row:hover {
  background-color: #f7f8fa; /* 鼠标悬停时行高亮 */
}

/* 弹窗底部样式 */
.dialog-footer {
  padding: 14px 20px;
  background-color: #f4f6f9;
  text-align: center;
  border-top: 1px solid #e4e8f1;
}

.el-pagination {
  margin-top: 10px;
}

.el-pagination .el-pager li {
  padding: 6px 12px;
  font-size: 14px;
  color: #409eff;
}

.el-pagination .el-pager li.active {
  background-color: #409eff;
  color: white;
}

.el-pagination .el-pager li:hover {
  background-color: #66b1ff;
}

.valid-fill-count {
  margin-top: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #409eff; /* 高亮显示有效填写人次 */
}
</style>



